<!DOCTYPE html>
<style>
  * {
    box-sizing: border-box;
    overscroll-behavior: none;
  }
  html {
    margin: 0;
    font-family: -apple-system, BlinkMacSystemFont;
    color: CanvasText;
    color-scheme: light dark;
    font-size: 12px;
  }
  body {
    margin: 0;
  }
  h1 {
    margin: 1rem;
    font-weight: 100;
  }
  section {
    margin: 1rem;
  }
  button, input {
    border: none;
    border-radius: 3px;
    padding: .5rem;
  }
  button, input, textarea {
    font-size: 1rem;
    background: Canvas;
  }
  textarea {
    padding: 1rem 1.5rem;
    width: 100%;
    border: none;
    resize: none;
    font-family: monospace;
  }
  button[disabled], input[disabled] {
    opacity: .5;
    cursor: not-allowed;
  }
  .right {
    float: right;
  }
</style>

<h1>Configure your <b>Multi</b> app</h1>
<section>
  <input id="name" type="text" placeholder="App Name" autofocus>
  <button id="icon">Select Icon</button>
  <label for="icon">
    <em id="path"></em>
  </label>
</section>
<textarea id="json" placeholder="JSON Configuration" rows="15" spellcheck="false"></textarea>
<section>
  <button id="save" class="right" disabled>Save</button>
  <em id="error"></em>
</section>

<script>
  let iconPath = ""
  let jsonError = ""

  const name = document.getElementById("name")
  const icon = document.getElementById("icon")
  const path = document.getElementById("path")
  const json = document.getElementById("json")
  const save = document.getElementById("save")
  const error = document.getElementById("error")

  name.addEventListener("input", () => {
    update()
  })
  icon.addEventListener("click", () => {
    webkit.messageHandlers.icon.postMessage({})
      .then((x) => iconPath = x, (e) => console.error(e))
      .then(update)
  })
  json.addEventListener("input", () => {
    webkit.messageHandlers.json.postMessage(json.value)
      .then(() => jsonError = "", (e) => jsonError = e.toString())
      .then(update)
  })
  save.addEventListener("click", () => {
    webkit.messageHandlers.save.postMessage({ name: name.value, icon: iconPath, json: json.value })
      .catch((e) => error.innerText = e.toString())
  })

  function update() {
    path.innerText = iconPath
    error.innerText = jsonError
    save.disabled = !name.value || !!jsonError
  }
</script>
